﻿using MotorLibrary.DAL;
using MotorLibrary.Error;
using MotorLibrary.Repository;
using MotorLibrary.Repository.DTO;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace MotorLibrary.Service
{
    public class VariableService : IVariableService
    {
        private IVariableRepository _variableRepository;
        private IEndpointRepository _endPointRepository;

        public VariableService(IVariableRepository variableRepository, IEndpointRepository endPointRepository)
        {
            this._variableRepository = variableRepository;
            this._endPointRepository = endPointRepository;
        }

        public VariableDTO Read(long id)
        {
            return _variableRepository.Read(id);
        }

        public IList<VariableDTO> List()
        {
            return _variableRepository.List();
        }

        public VariableDTO Create(VariableDTO dto)
        {
            ChequeaExisteEndPoint(dto.EndpointID);

            return _variableRepository.Create(dto);
        }

        private void ChequeaExisteEndPoint(long EndpointID)
        {
            EndpointDTO checkDTO = _endPointRepository.Read(EndpointID);

            if (checkDTO == null)
            {
                throw new NoEncontradaException(EndpointID, "No existe el endpoint especificado");
            }
            else if (checkDTO.Procesar == false)
            {
                throw new NoEncontradaException(EndpointID, "El endpoint no acepta el procesado");
            }
        }

        public VariableDTO Update(VariableDTO dto)
        {
            return _variableRepository.Update(dto);
        }

        public VariableDTO Delete(long id)
        {
             return _variableRepository.Delete(id);
        }

        public IList<VariableDTO> FilterByEndpoint(long EndpointID)
        {
            return _variableRepository.Filter(variable => variable.EndpointID == EndpointID);
        }
    }
}
